package com.rock.upms.svc.upms.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rock.common.annotation.ANNBaseService;
import com.rock.common.base.BaseConstants;
import com.rock.common.base.BaseResult;
import com.rock.upms.api.model.service.IUpmsDepartmentService;
import com.rock.upms.api.model.service.IUpmsPermissionService;
import com.rock.upms.api.model.service.IUpmsPersonService;
import com.rock.upms.api.model.service.IUpmsSystemService;
import com.rock.upms.api.model.service.IUpmsThirdBindService;
import com.rock.upms.api.model.service.IUpmsUserService;
import com.rock.upms.api.upms.service.ILoginService;
import com.rock.upms.api.upms.service.IUpmsService;
import com.rock.upms.model.UpmsDepartment;
import com.rock.upms.model.UpmsDepartmentExample;
import com.rock.upms.model.UpmsPermission;
import com.rock.upms.model.UpmsPerson;
import com.rock.upms.model.UpmsPersonExample;
import com.rock.upms.model.UpmsRole;
import com.rock.upms.model.UpmsRolePermission;
import com.rock.upms.model.UpmsSystem;
import com.rock.upms.model.UpmsThirdBind;
import com.rock.upms.model.UpmsThirdBindExample;
import com.rock.upms.model.UpmsThirdBindExample.Criteria;
import com.rock.upms.model.UpmsUser;
import com.rock.upms.model.UpmsUserExample;
import com.rock.upms.model.UpmsUserPermission;
import com.rock.upms.model.dto.PermissionDto;
import com.rock.upms.model.dto.RoleDto;
import com.rock.upms.model.dto.UserDto;
import com.rock.upms.model.dto.UserInfo;
import com.rock.upms.svc.dao.dto.mapper.UpmsApiMapper;

@ANNBaseService
@Service
public class UpmsService implements IUpmsService {

	private static Logger log = LoggerFactory.getLogger(UpmsService.class);

	@Override
	public void initMapper() {
		// this.mapper = upmsApiMapper;
		log.trace("===>UpmsService  init");
	}

	@Autowired
	private UpmsApiMapper upmsApiMapper;
	@Autowired
	private ILoginService loginService;
	@Autowired
	private IUpmsPermissionService upmsPermissionService;
	@Autowired
	private IUpmsDepartmentService upmsDepartmentService;
	@Autowired
	private IUpmsUserService upmsUserService;
	@Autowired
	private IUpmsThirdBindService upmsThirdBindService;
	@Autowired
	private IUpmsPersonService upmsPersonService;
	@Autowired
	private IUpmsSystemService upmsSystemService;

	@Override
	public List<UpmsPermission> getPermissionByUserId(Integer ouUserId) {
		// TODO Auto-generated method stub
		return upmsApiMapper.selectPermissionByUserId(ouUserId);
	}

	@Override
	public List<UpmsRole> getRoleByUserId(Integer ouUserId) {
		// TODO Auto-generated method stub
		return upmsApiMapper.selectRoleByUserId(ouUserId);
	}

	/**
	 * 功能：获取子机构<br/>
	 * 说明：利用递归的形式获取子机构
	 * 
	 * 
	 * @param pid
	 *            父机构id
	 * @author zhousq
	 * @version 创建时间：2017-11-11 14:04:37
	 * @return 带顺序的机构列表List<UpmsDepartment>
	 */
	@Override
	public List<UpmsDepartment> getChildDepartment(int pid) {
		List<UpmsDepartment> tempList = new ArrayList<>();
		UpmsDepartmentExample deptExample = new UpmsDepartmentExample();
		deptExample.or().andPidEqualTo(pid);
		deptExample.setOrderByClause(" seqno asc ");
		List<UpmsDepartment> deptList = upmsDepartmentService.selectByExample(deptExample);
		if (deptList != null) {
			for (UpmsDepartment od : deptList) {
				tempList.add(od);
				// 递归获取子机构
				tempList.addAll(getChildDepartment(od.getId()));
			}
		}
		return tempList;
	}

	

	@Override
	public UpmsDepartment getRootDepartment() {
		UpmsDepartmentExample example = new UpmsDepartmentExample();
		// pid=0的为根机构
		example.or().andPidEqualTo(0);
		return upmsDepartmentService.selectFirstByExample(example);
	}

	@Override
	public List<UpmsDepartment> getDepartmentByUsercode(String usercode) {
		UpmsUserExample userExample = new UpmsUserExample();
		userExample.or().andUsercodeEqualTo(usercode);
		List<UpmsUser> userList = upmsUserService.selectByExample(userExample);
		List<Integer> listId = new ArrayList<>();
		for (int i = 0; i < userList.size(); i++) {
			listId.add(userList.get(i).getDepartmentId());
		}
		UpmsDepartmentExample example = new UpmsDepartmentExample();
		example.or().andIdIn(listId);
		example.setOrderByClause(" dept_code asc ");
		return upmsDepartmentService.selectByExample(example);
	}

	@Override
	public UpmsUser getDefaultUser(String usercode) {
		UpmsUserExample example = new UpmsUserExample();
		example.or().andUsercodeEqualTo(usercode).andIsDefaultEqualTo("1");// 1为默认
		return upmsUserService.selectFirstByExample(example);
	}

	@Override
	public UpmsDepartment getDefaultDepartment(String usercode) {
		UpmsUser user = getDefaultUser(usercode);
		if (user != null) {
			return upmsDepartmentService.selectByPrimaryKey(user.getDepartmentId());
		} else {
			return null;
		}
	}

	@Override
	public List<UpmsRolePermission> getRolePermisstionByRoleId(Integer roleId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<UpmsUserPermission> getUserPermissionByUserId(Integer userId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseResult thirdBind(UpmsThirdBind upmsThirdBind) {
		// third_code||openid 唯一 ,一个openid 只能绑定一个手机号
		UpmsThirdBindExample example = new UpmsThirdBindExample();
		Criteria criteria = example.createCriteria();
		criteria.andThirdComcodeEqualTo(upmsThirdBind.getThirdComcode());
		criteria.andThirdIdEqualTo(upmsThirdBind.getThirdId());
		criteria.andIsDeletedEqualTo(BaseConstants.NOT_DELETED);
		UpmsThirdBind queryBind = upmsThirdBindService.selectFirstByExample(example);
		if (queryBind != null) {
			return BaseResult.fail("该绑定信息已存在，绑定的手机号为：" + queryBind.getMobilephone());
		} else {
			// 判断手机号是否在upms_person表中存在
			UpmsPersonExample personExample = new UpmsPersonExample();
			personExample.createCriteria().andMobilephoneEqualTo(upmsThirdBind.getMobilephone()).andIsDeletedEqualTo("0");
			UpmsPerson person = upmsPersonService.selectFirstByExample(personExample);
			if (person != null) {
				int id = upmsThirdBindService.insert(upmsThirdBind);
				if (id != 0) {
					return BaseResult.success("绑定成功");
				} else {
					return BaseResult.fail("插入绑定信息失败");
				}
			} else {
				return BaseResult.fail("绑定的手机号员工信息表中不存在");
			}
		}
	}

	/**
	 * 根据UpmsUser数据库实体对象获取userinfo
	 * 
	 * @param upmsUser
	 * @return
	 */
	@Override
	public UserInfo getUserInfoByUpmsUser(UpmsUser upmsUser) {
		UserInfo userInfo = new UserInfo();
		UpmsPersonExample personExample = new UpmsPersonExample();
		personExample.or().andUsercodeEqualTo(upmsUser.getUsercode());
		UpmsPerson person = upmsPersonService.selectFirstByExample(personExample);
		UpmsDepartment department = upmsDepartmentService.selectByPrimaryKey(upmsUser.getDepartmentId());
		UserDto sessionUser = new UserDto();
		sessionUser.setId(upmsUser.getId());
		sessionUser.setUsercode(upmsUser.getUsercode());
		sessionUser.setUsername(upmsUser.getUsername());
		sessionUser.setRealname(upmsUser.getRealname());
		sessionUser.setSex(person.getSex());
		sessionUser.setDeptCode(department.getDeptCode());
		sessionUser.setDeptName(department.getDeptName());
		sessionUser.setWorkType(upmsUser.getWorkType());
		sessionUser.setAvatar(person.getAvatar());
		sessionUser.setSalt(person.getSalt());
		userInfo.setUser(sessionUser);
		// 登录人的全局角色信息
		List<UpmsRole> upmsRoleList = this.getRoleByUserId(upmsUser.getId());
		List<RoleDto> roleDtoList = new ArrayList<RoleDto>();
		for (UpmsRole upmsRole : upmsRoleList) {
			RoleDto roleDto = new RoleDto();
			roleDto.setId(upmsRole.getId());
			roleDto.setRoleCode(upmsRole.getRoleCode());
			roleDto.setRoleName(upmsRole.getRoleName());
			if (upmsRole.getSystemId() == 0) {
				roleDto.setSystemCode("0");
			} else {
				String systemcode = getSystemCodeById(upmsRole.getSystemId());
				if (systemcode != null) {
					roleDto.setSystemCode(systemcode);
				} else {
					continue;// 不是全局角色且没关联系统的，不加入
				}
			}
			roleDtoList.add(roleDto);
		}
		userInfo.setRoleList(roleDtoList);// 装载角色列表
		// 登录人的全局权限信息
		List<UpmsPermission> upmsPermissionList = this.getPermissionByUserId(upmsUser.getId());
		List<PermissionDto> permissionDtoList = new ArrayList<PermissionDto>();
		for (UpmsPermission upmsPermission : upmsPermissionList) {
			String syscode = getSystemCodeById(upmsPermission.getSystemId());
			if (syscode == null) {
				continue;
			} else {
				PermissionDto permissionDto = new PermissionDto();
				permissionDto.setId(upmsPermission.getId());
				permissionDto.setName(upmsPermission.getName());
				permissionDto.setPermissionValue(upmsPermission.getPermissionValue());
				permissionDto.setSystemCode(syscode);
				permissionDtoList.add(permissionDto);
			}
		}
		userInfo.setPermissionList(permissionDtoList);// 装载角色列表
		return userInfo;
	}

	/**
	 * 根据系统id获取系统code
	 * 
	 * @param id
	 * @return
	 */
	private String getSystemCodeById(Integer id) {
		UpmsSystem upmsSystem = upmsSystemService.selectByPrimaryKey(id);
		if (upmsSystem != null) {
			return upmsSystem.getSystemCode();
		}
		return null;
	}
}
